import { defineStore } from "pinia";
import { store } from "@/store";
import {
  ACCESS_TOKEN,
  CURRENT_USER,
  IS_SCREENLOCKED,
} from "@/store/mutation-type";

import { getUserInfo, login, logout, register } from "@/api/login";
import { storage } from "@/utils/storage";
// import { useAsyncRouteStore } from '@/store/modules/asyncRoute';
export type UserInfoType = {
  id: string;
  username: string;
  realName: string;
  avatar: string;
};

export interface UserState {
  token: string;
  username: string;
  avatar: string;
  permissions: any[];
  info: UserInfoType;
}

export const useUserStore = defineStore("app-user", {
  state: (): UserState => ({
    token: storage.get(ACCESS_TOKEN, ""),
    username: "",
    avatar: "",
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions: any) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    // 登录
    async login(params: any) {
      const { result } = await login(params);
      if (result && result.token !== undefined) {
        const ex = result.expiration || 24 * 60 * 60;
        storage.set(ACCESS_TOKEN, result.token, ex);
        storage.set(IS_SCREENLOCKED, false);
        this.setToken(result.token);
      }
      return result;
    },
    // 注册
    async register(params: any) {
      return await register(params);
    },

    // 获取用户信息
    async getInfo() {
      try {
        const { result } = await getUserInfo();
        console.log(`user`, result);
        if (result && result.perms !== null && result.perms.length) {
          this.setPermissions(result.perms);
          this.setUserInfo(result);
        } else {
          this.setPermissions([]);
        }
        this.setUserInfo(result);
        this.setAvatar(result.avatar);
        return result;
      } catch (e) {
        console.error(e);
        await this.logout();
      }
    },

    // 登出
    async logout() {
      await logout();
      this.setPermissions([]);
      this.setToken("");
      this.setAvatar("");
      this.setUserInfo({
        id: "",
        username: "",
        realName: "",
        avatar: "",
      });
      storage.clear();

      //   const routerStore = useAsyncRouteStore();
      //   routerStore.clear();
    },
  },
});

export function useUser() {
  return useUserStore(store);
}
